package cn.edu.zzuli.nothinglink.service.impl;

import cn.edu.zzuli.nothinglink.entity.R;
import cn.edu.zzuli.nothinglink.service.NoticeService;
import cn.edu.zzuli.nothinglink.utils.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDateTime;

@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public R putNotice(JSONObject json) {
        Integer courseId = json.getInteger("courseId");
        String msg = json.getString("msg");
        if (StringUtils.isEmpty(msg)) return R.error().add("error", "不要传空");
        try {

            LocalDateTime endTime = json.getObject("endTime", LocalDateTime.class);

            LocalDateTime now = LocalDateTime.now();
            if (now.isAfter(endTime)) return R.error().add("error", "发布的时间，请在当前时间之后");
            Duration duration = Duration.between(now, endTime);

            redisUtil.set("course:notice:"+courseId, msg, duration.getSeconds());
        } catch (Exception e) {
            return R.error().add("error", "注意日期格式");
        }
        return R.success();
    }

    public R getNotice(Integer courseId) {
        Object o = redisUtil.get("course:notice:" + courseId);
        if (o == null) return R.success().add("notice", "暂无公告哦！～");
        else return R.success().add("notice", o.toString());
    }
}
